from shapely.geometry import Point, Polygon
import random
import logging

logger = logging.getLogger('gunicorn.error')

def point_in_segmentation(point, segmentation):
    point = Point(point)
    points = [(segmentation[i], segmentation[i+1]) for i in range(0, len(segmentation), 2)]
    if(len(points) > 2):
        polygon = Polygon(points)
        return polygon.contains(point)
    else:
        return False

def annotations_containing_point(point, annotations):
    containing_annotations = []
    for annotation in annotations:
        for segmentation in annotation['segmentation']:
            if point_in_segmentation(point, segmentation):
                containing_annotations.append(annotation)

    if containing_annotations:
        return random.choice(containing_annotations)
    else:
        return None